<template>


  <div class="container">
    <img width="60%" height="100%" :src="bg" style="position:absolute; left:0; top:0; z-index:-1;"/>
    <div style="width: 60%; "></div>
    <div class="login">
      <div style="width: 300px; height: 400px; margin-bottom: 200px">
        <n-tabs
            class="card-tabs"
            size="large"
            animated
        >
          <n-tab-pane name="signin" tab="登录">
            <n-form v-if="loginByCode" ref="loginFormRef" :model="loginCodeData" :rules="loginCodeRules">
              <n-form-item-row path="phone" label="手机号码">
                <n-input v-model:value="loginCodeData.phone" placeholder="请输入手机号"/>
              </n-form-item-row>
              <n-form-item-row path="code" label="验证码">
                <n-input v-model:value="loginCodeData.code" placeholder="请输入验证码"/>
                <p class="showCode" @click="getCodeBtn">{{codeDetailData}}</p>
              </n-form-item-row>
            </n-form>
            <n-form v-else ref="loginFormRef" :model="loginData" :rules="loginRules">
              <n-form-item-row path="phone" label="手机号">
                <n-input v-model:value="loginData.phone" placeholder="请输入手机号"/>
              </n-form-item-row>
              <n-form-item-row path="password" label="密码">
                <n-input v-model:value="loginData.password" type="password" show-password-on="click" placeholder="请输入密码"/>
              </n-form-item-row>
            </n-form>
            <n-button type="primary" block secondary strong @click="login">
              登录
            </n-button>
            <div class="otherLogin">
                <p v-if="loginByCode"><span @click="loginByCode=!loginByCode">账号登录</span></p>
                <p v-else><span @click="loginByCode=!loginByCode">验证码登录</span></p>
            </div>
          </n-tab-pane>
          <n-tab-pane name="signup" tab="注册">
            <n-form ref="registerFormRef" :model="registerData" :rules="registerRules">
              <n-form-item-row label="用户名" path="username">
                <n-input v-model:value="registerData.username"/>
              </n-form-item-row>
              <n-form-item-row path="phone" label="手机号码">
                <n-input v-model:value="registerData.phone" placeholder="请输入手机号"/>
              </n-form-item-row>
              <n-form-item-row label="密码" path="password">
                <n-input v-model:value="registerData.password" type="password" show-password-on="click"/>
              </n-form-item-row>
              <n-form-item-row label="重复密码" path="rePassword">
                <n-input v-model:value="registerData.rePassword" type="password" show-password-on="click"/>
              </n-form-item-row>
            </n-form>
            <n-button type="primary" block secondary strong @click="register">
              注册
            </n-button>
          </n-tab-pane>
        </n-tabs>
      </div>


    </div>
  </div>

</template>

<script setup>
import bg from '@/assets/bg.jpeg'
import {ref,watch} from 'vue'
import {createDiscreteApi} from 'naive-ui'
import {useRouter} from "vue-router";


const loginByCode = ref(true)
const codeDetailData = ref("获取验证码")
let loginCodeData = ref({
  phone:'',
  code:''
})
let loginData = ref({
  phone: "",
  password: ""
})
let registerData = ref({
  username: "1",
  phone:"",
  password:"123123",
  rePassword: "123123"
})

// 监听器
watch(loginByCode,(newVal,oldVal)=>{
  // 切换登录方式时,重置输入框内容
  loginCodeData.value.code=""
  loginCodeData.value.phone=""
  loginData.value.phone=""
  loginData.value.password=""
})

const validatePasswordLength = (rule, value) => {
  if (value.length >= 6 && value.length <= 13)
    return true
  return false
}
const validateCodeLength = (rule,value)=>{
  if (value.length == 6)
    return true
  return false
}
const validateRepassword = (rule, value) => {
  return value === registerData.value.password
}
const loginRules = {
  phone: [
    {
      required: true,
      message: "请输入手机号",
      trigger: ["input", "blur"]
    },
    // {
    //   validator: validatePasswordLength,
    //   message: "用户名长度必须在6-13位之间",
    //   trigger: ["input", "blur"]
    // }
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: ["input", "blur"]
    },
    {
      validator: validatePasswordLength,
      message: "密码长度必须在6-13位之间",
      trigger: ["input", "blur"]
    }
  ]
}
const loginCodeRules = {
  phone:[
    {
      required: true,
      message: "请输入手机号",
      trigger: ["input", "blur"]
    }
  ],
  code:[
    {
      required: true,
      validator: validateCodeLength,
      message: "请输入6位验证码",
      trigger: ["input", "blur"]
    }
  ]
}
const registerRules = {
  username: [
    {
      required: true,
      message: "请输入用户名",
      trigger: ["input", "blur"]
    },
    // {
    //   validator: validatePasswordLength,
    //   message: "用户名长度必须在6-13位之间",
    //   trigger: ["input", "blur"]
    // }
  ],
  phone:[
    {
      required: true,
      message: "请输入手机号",
      trigger: ["input", "blur"]
    }
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: ["input", "blur"]
    },
    {
      validator: validatePasswordLength,
      message: "密码长度必须在6-13位之间",
      trigger: [ "blur"]
    }
  ],
  rePassword: [
    {
      required: true,
      message: "请输入重复密码",
      trigger: ["blur"]
    },
    {
      validator: validateRepassword,
      message: "密码输入不一致",
      trigger: ["blur"]
    }
  ]
}

// 点击验证码按钮
let timeOut = ref(120)
let timer = null
const timeFuc = ()=>{
  timer = setInterval(()=>{
    if(timeOut.value>0){
      timeOut.value--;
    }else{
      clearInterval(timer)
      timeOut.value=120
      codeDetailData.value="获取验证码"
    }
  },1000)
}
// 获取验证码
const getCodeBtn = async()=>{
  if(codeDetailData.value == "获取验证码"){
    if(loginCodeData.value.phone == ''){ return message.warning("请先输入手机号")}
    const phoneRegexp = /^1\d{10}$/
    if(!phoneRegexp.test(loginCodeData.value.phone)){ return message.warning("请检查手机号格式")}

    let res = await getCodeAPI(loginCodeData.value.phone)
    codeDetailData.value=res.data
    timeFuc()
  }else{
    message.warning(timeOut.value+"s后可重新获取验证码")
  }
}

const {message} = createDiscreteApi(
    ["message", 'dialog', 'notification', 'loadingBar', 'modal']
)

const loginFormRef = ref()
const registerFormRef = ref()
import {userLoginAPI, userRegisterAPI,userLoginByCodeAPI,getCodeAPI} from "@/api/user.js";
import {useTokenStore} from "@/stores/token.js";

// 注册
const register = (e)=>{
  registerFormRef.value?.validate(async (errors) => {
    if (!errors){
      const result = await userRegisterAPI(registerData.value)
      message.success("注册成功！！")
    }
  })
}


const tokenStore = useTokenStore()
const router = useRouter()
// 登录
const login = (e)=>{
  loginFormRef.value?.validate(async (errors) => {
    if (!errors){
      if(loginByCode.value){
        const result = await userLoginByCodeAPI(loginCodeData.value)
        tokenStore.setToken(result.data)
        message.success("使用验证码登录成功！")
        router.push('/home/gl')
      }else{
        const result = await userLoginAPI(loginData.value)
        tokenStore.setToken(result.data)
        message.success("使用密码登录成功！")
        router.push('/home/gl')
      }
    }
  })
}

</script>

<style lang="less" scoped>
.container {
  width: 100vw;
  height: 100vh;
  display: flex;
  .login {
    display: flex;
    width: 40vw;
    height: 100vh;
    justify-content: center;
    align-items: center;
    .otherLogin{
      color: #999;
      margin: 20px 0;
      p{
        text-align: right;
        span{
          cursor: pointer;
          &:hover{
            color: #666;
          }
        }
      }
    }
    .card-tabs{
      .n-input{
        height: 34px;
        line-height: 34px;
      }
      
      .showCode{
        width: 140px;
        height: 34px;
        line-height: 34px;
        text-align: center;
        background: @mainBackground;
        color: @mainColor;
        border-radius: 4px;
        margin-left: 10px;
        cursor: pointer;
      }
    }
  }
}


</style>